package com.hwy.simple.chart.line_chart

import android.content.res.Resources
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.fastjson.JSONObject
import com.hwy.chart.LineChartView
import com.hwy.chart.component.DoubleLineChartComponent
import com.hwy.chart.component.LineChartComponent
import com.hwy.chart.coordinate.axis.AxisTag
import com.hwy.chart.coordinate.axis.BaseAxis
import com.hwy.chart.cursor.BaseCursor
import com.hwy.simple.chart.R
import com.hwy.simple.chart.http.HttpUtil

/**
 * 折线图页面
 */
class LineChartActivity : AppCompatActivity(), HttpUtil.HttpCallback {

    companion object {
        private const val TAG = "LineChartActivity"
        const val totalBuy = "totalBuy"
        const val shBuy = "shBuy"
        const val szBuy = "szBuy"
        const val szShBuy = "szShBuy"
    }

    private lateinit var lineChartView: LineChartView

    private var lineChartLegend: LineChartLegend? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_line_chart)
        supportActionBar?.title = "折线图"

        lineChartView = findViewById(R.id.line_chart_view)
        initLineChartView()
        initFlag()

        Handler(Looper.getMainLooper()).postDelayed({ request() }, 1000)
    }

    private fun initLineChartView() {
        lineChartView.run {
            TextView(context).run {
                // EmptyView
                text = "加载中.."
                textSize = 16F
                setBackgroundColor(Color.parseColor("#EEEEEE"))
                setTextColor(Color.GRAY)
                gravity = Gravity.CENTER
                addEmptyView(this)
            }

            // legend
            LayoutInflater.from(context).inflate(R.layout.layout_chart_legend, this, false)?.run {
                (this as? LineChartLegend)?.run {
                    cursor.addCursorChangeListener(this)
                    lineChartLegend = this
                }
                addLegendView(
                    this,
                    FrameLayout.LayoutParams(dp2Px(160F), ViewGroup.LayoutParams.WRAP_CONTENT)
                )
            }


            // 设置横向光标不显示
            cursor.run {
                cursorModel = BaseCursor.MODEL_VERTICAL
                cursorColor = Color.RED
                cursorWidth = 2F
            }

            getYAxis<Float>().run {
                axisWidth = BaseAxis.INVALID_AXIS_WIDTH
                tagCount = 5
                axisTag.run {
                    axisOffset = 8
                    axisModel = AxisTag.MODEL_INNER
                }
            }

            getXAxis<String>().run {
                axisWidth = BaseAxis.INVALID_AXIS_WIDTH
                axisTag.run {
                    axisOffset = 8
                    addTagList(arrayListOf("09:20", "12:00/13:00", "16:10"))
                }
            }

            // 网格线设置
            coordinate.gridLine.run {
                lineColor = Color.GRAY
                setDashPathEffect(floatArrayOf(8F, 10F))
                setLineCount(0, 5)
            }

            // 添加组件
            addComponent(totalBuy, LineChartComponent<Float>(this).apply {
                lineColor = Color.parseColor("#3366FF")
//                isShow = false
                // 支持阴影效果
                isDrawShadow = true
                // 设置阴影的起始/结束颜色
                setGradient(
                    Color.parseColor("#883366FF"),
                    Color.parseColor("#003366FF")
                )

                // 光标和组件交点
                componentFocus.run {
                    radius = 8F
                    strokeWidth = 3F
                    strokeColor = Color.parseColor("#3366FF")
                    innerColor = Color.WHITE
                }
            })
            addComponent(shBuy, LineChartComponent<Float>(this).apply {
                lineColor = Color.parseColor("#CC41D9")
//                isShow = false
                // 光标和组件交点
                componentFocus.run {
                    radius = 8F
                    strokeWidth = 3F
                    strokeColor = Color.parseColor("#CC41D9")
                    innerColor = Color.WHITE
                }
            })
            addComponent(szBuy, LineChartComponent<Float>(this).apply {
                lineColor = Color.parseColor("#14CCBD")
//                isShow = false

                // 光标和组件交点
                componentFocus.run {
                    radius = 8F
                    strokeWidth = 3F
                    strokeColor = Color.parseColor("#14CCBD")
                    innerColor = Color.WHITE
                }
            })
            addComponent(szShBuy, DoubleLineChartComponent<Float>(this).apply {
                lineColor = Color.parseColor("#CC41D9")
                secondLineColor = Color.parseColor("#14CCBD")
                lineWidth = 4F
                isDrawShadow = true
                isShow = true

                // 设置阴影的起始/结束颜色
                setGradient(
                    Color.parseColor("#883366FF"),
                    Color.parseColor("#883366FF")
                )

                // 光标和组件交点
                componentFocus.run {
                    radius = 8F
                    strokeWidth = 3F
                    strokeColor = Color.parseColor("#14CCBD")
                    innerColor = Color.WHITE
                }
            })
        }
    }

    private fun updateChartComponent(chartBean: LineChartBean?) {
        chartBean?.let { bean ->
            lineChartView.run {
                getComponent<Float>(totalBuy)?.run {
                    updateComponentDataList(bean.data.total_net_buy_list)
                }
                getComponent<Float>(shBuy)?.run {
                    updateComponentDataList(bean.data.sh_net_buy_list)
                }
                getComponent<Float>(szBuy)?.run {
                    updateComponentDataList(bean.data.sz_net_buy_list)
                }
                getComponent<Float>(szShBuy)?.run {
                    updateComponentDataList(bean.data.sh_net_buy_list)
                    (this as? DoubleLineChartComponent<Float>)?.run {
                        updateComponentSecondDataList(bean.data.sz_net_buy_list)
                    }
                }
                getXAxis<String>().updateAxisData(bean.data.net_buy_time_list)
                lineChartLegend?.lineChartBean = bean
                requestLayout()
                invalidate()
            }
        }
    }

    private fun request() {
        val url =
            "https://apigate.10jqka.com.cn/d/hq/hshkconnect/captitalflows/timedia/get_timedia?type=south"
        HttpUtil.request(url, this)
    }

    override fun onSuccess(json: String?) {
        if (isFinishing) {
            return
        }
        json?.run {
            val lineChartBean = JSONObject.parseObject(this, LineChartBean::class.java)
            Log.d(TAG, "onSuccess: ${lineChartBean.status_msg}")
            updateChartComponent(lineChartBean)
        }

    }

    override fun onFailure(msg: String?) {
        Log.d(TAG, "on failure: $msg")
    }

    fun dp2Px(dp: Float): Int {
        val scale: Float = Resources.getSystem().displayMetrics.density
        return (dp * scale + 0.5f).toInt()
    }

    fun onBtnClick(view: View) {
        when (view.id) {
            R.id.btn_total_buy -> {
                lineChartView.getComponent<Float>(totalBuy)?.run {
                    isShow = !isShow
                    findViewById<Button>(R.id.btn_total_buy).text =
                        "全部(${if (isShow) "开" else "关"})"
                }
            }
            R.id.btn_sh_buy -> {
                lineChartView.getComponent<Float>(shBuy)?.run {
                    isShow = !isShow
                    findViewById<Button>(R.id.btn_sh_buy).text =
                        "沪股通(${if (isShow) "开" else "关"})"
                }
            }
            R.id.btn_sz_buy -> {
                lineChartView.getComponent<Float>(szBuy)?.run {
                    isShow = !isShow
                    findViewById<Button>(R.id.btn_sz_buy).text =
                        "深股通(${if (isShow) "开" else "关"})"
                }
            }
            R.id.btn_double -> {
                lineChartView.getComponent<Float>(szShBuy)?.run {
                    isShow = !isShow
                    findViewById<Button>(R.id.btn_double).text =
                        "双线(${if (isShow) "开" else "关"})"
                }
            }
        }
    }

    private fun initFlag() {
        lineChartView.getComponent<Float>(totalBuy)?.run {
            findViewById<Button>(R.id.btn_total_buy).text =
                "全部(${if (isShow) "开" else "关"})"
        }
        lineChartView.getComponent<Float>(shBuy)?.run {
            findViewById<Button>(R.id.btn_sh_buy).text =
                "沪股通(${if (isShow) "开" else "关"})"
        }
        lineChartView.getComponent<Float>(szBuy)?.run {
            findViewById<Button>(R.id.btn_sz_buy).text =
                "深股通(${if (isShow) "开" else "关"})"
        }
        lineChartView.getComponent<Float>(szShBuy)?.run {
            findViewById<Button>(R.id.btn_double).text =
                "双线(${if (isShow) "开" else "关"})"
        }
    }

}